import React, { useState, useEffect, useMemo, useContext } from 'react';
import {
  Table,
  Card,
  Button,
  Space,
  Typography,
  Popover,
  Checkbox,
  Dropdown,
  Menu,
  Switch,
  PaginationProps,
} from '@arco-design/web-react';
import { IconFilter, IconDownload } from '@arco-design/web-react/icon';
import { getColumns } from './constants';
import { GlobalContext } from '@/context';
import useLocale from '@/utils/useLocale';
import SearchForm from './form';
import locale from './locale';
import styles from './style/index.module.less';
import { Search, Export } from '@/api/modules/otprequest';
import { OTPSearch } from '@/api/interface/otprequest';
import { useDownload } from '@/utils/useDownload';
import { ReqPage } from '@/api/interface';
import useStorageJson from '@/utils/useStorageJson';
import { useSelector } from 'react-redux';
import { GlobalState } from '@/store';
import isEmpty from 'lodash/isEmpty';
import debounce from 'lodash/debounce';
import { SorterInfo } from '@arco-design/web-react/es/Table/interface';

const { Group } = Checkbox;
const { Title } = Typography;

function OPTRequest() {
  const t = useLocale(locale);
  const { rtl, lang } = useContext(GlobalContext);

  const { userInfo } = useSelector((state: GlobalState) => state);
  const [tableColumns, setTableColumns] = useStorageJson(
    `${userInfo.id}_otprequest_tableColumns`,
    [
      'id',
      'fullName',
      'applicantType',
      'email',
      'mobile',
      'createdAt',
      'expiredAt',
    ]
  );

  const columns = useMemo(
    () => getColumns(t, lang, tableColumns),
    [t, tableColumns]
  );

  const [data, setData] = useState<OTPSearch[]>([]);

  const [pagination, setPatination] = useState<PaginationProps>({
    sizeOptions: [10, 20, 50, 100],
    sizeCanChange: true,
    showTotal: true,
    pageSize: 10,
    current: 1,
    pageSizeChangeResetCurrent: true,
  });

  const [loading, setLoading] = useState(true);
  const [withoutTickets, setWithoutTickets] = useState(false);
  const [formParams, setFormParams] = useState<ReqPage & any>({
    pageSize: 10,
    pageNo: 1,
  });

  useEffect(() => {
    fetchData();
  }, [
    withoutTickets,
    pagination.current,
    pagination.pageSize,
    JSON.stringify(formParams),
  ]);

  async function fetchData() {
    const { current, pageSize } = pagination;
    setLoading(true);
    try {
      const res = await Search({
        ...formParams,
        pageNo: current,
        pageSize,
        withoutTickets,
      });
      setData(res.data.data);
      setPatination({
        ...pagination,
        pageSize,
        current,
        total: res.data.count,
      });
    } finally {
      setLoading(false);
    }
  }

  function onChangeTable({ current, pageSize }, sorter: SorterInfo) {
    const { direction, field } = sorter;
    if (direction) {
      const sort = [];
      const obj = Object.create({});
      if (field == 'createdAt') obj.field = 'created_at';
      if (field == 'expiredAt') obj.field = 'ticket_create_time';
      obj.asc = direction == 'ascend';
      sort.push(obj);
      setFormParams({ ...formParams, sort });
    } else {
      const updatedFormParams = { ...formParams, sort: undefined };
      delete updatedFormParams.sort;
      setFormParams(updatedFormParams);
    }
    setPatination({
      ...pagination,
      current,
      pageSize,
    });
  }

  const handleSearch = debounce((params) => {
    if (params.expiredAt) {
      params.start = params.expiredAt[0];
      params.end = params.expiredAt[1];
    }
    if (loading && isEmpty(params)) return;
    setPatination({ ...pagination, current: 1 });
    setFormParams(params);
  }, 300);

  const filterOptions = [
    { label: '#', value: 'id', width: 60 },
    { label: t['searchTable.columns.fullName'], value: 'fullName', width: 160 },
    {
      label: t['searchTable.columns.complainant'],
      value: 'applicantType',
      width: 200,
    },
    { label: t['searchTable.columns.email'], value: 'email', width: 200 },
    { label: t['searchTable.columns.mobile'], value: 'mobile', width: 200 },
    { label: t['searchTable.columns.created'], value: 'createdAt', width: 200 },
    {
      label: t['searchTable.columns.violation'],
      value: 'expiredAt',
      width: 220,
    },
  ];
  const width = useMemo(
    () => {
      return columns.reduce((sum, { width = 0 }) => sum + width, 0) || 0;
    },
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [columns]
  );

  const tableColumnsFilter = () => (
    <Group
      direction="vertical"
      options={filterOptions.map((a) => {
        let disabled = false;
        if (tableColumns.length === 1) {
          disabled = tableColumns.includes(a.value);
        }

        return { ...a, disabled };
      })}
      value={tableColumns}
      onChange={(value) => {
        if (value.length < 1) {
          return;
        }
        setTableColumns(value);
      }}
    />
  );

  async function ExportExcel(e) {
    const params = {
      ...formParams,
      fields: tableColumns,
      withoutTickets,
    };
    await useDownload(
      Export,
      lang === 'ar-EG' ? 'طلب OTP' : 'OTPRequest',
      lang === 'ar-EG' ? 'ar' : 'en',
      e,
      e === 1 ? '.csv' : '.xlsx',
      params
    );
  }

  return (
    <Card className={rtl ? 'rtl' : ''}>
      {/* <Title heading={6} className={styles['page-title']}>
        {t['searchTable.form.title']}
      </Title> */}

      <SearchForm onSearch={handleSearch} rtl={rtl} />

      <div className={styles['button-group']}>
        <Space></Space>
        <Space>
          <Switch checked={withoutTickets} onChange={setWithoutTickets} />
          <span>{t['searchTable.operations.filter']}</span>
          <span></span>
          <Popover
            position="bottom"
            trigger="click"
            content={tableColumnsFilter}
          >
            <Button icon={<IconFilter />}>
              {t['searchTable.operation.filter']}
            </Button>
          </Popover>
          <Dropdown
            droplist={
              <Menu>
                <Menu.Item
                  key="1"
                  className={styles['export-text']}
                  onClick={() => ExportExcel(1)}
                >
                  CSV
                </Menu.Item>
                <Menu.Item
                  key="2"
                  className={styles['export-text']}
                  onClick={() => ExportExcel(2)}
                >
                  Excel
                </Menu.Item>
              </Menu>
            }
            position="bottom"
          >
            <Button type="primary" icon={<IconDownload />}>
              {t['searchTable.operations.export']}
            </Button>
          </Dropdown>
        </Space>
      </div>

      <Table
        border={{ wrapper: true, cell: true }}
        hover={true}
        rowKey="id"
        loading={loading}
        onChange={onChangeTable}
        pagination={pagination}
        columns={columns}
        data={data}
        scroll={{
          x: width,
        }}
        rowClassName={(record) => {
          return !record.expiredAt ? styles['table-custom-filter'] : '';
        }}
      />
    </Card>
  );
}

export default OPTRequest;
